package com.dongdongshop.quartz;

import com.dongdongshop.mapper.TbSeckillGoodsMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillGoodsExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @ClassName SeckillJob
 * @Author RC
 * @date 2021.01.06 14:25
 */
@Component
public class SeckillJob {
    @Resource
    private TbSeckillGoodsMapper tbSeckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    private static final Logger looger = LoggerFactory.getLogger(SeckillJob.class);

   @Scheduled(cron = " 0 0/1 * * * ? ")
   public void showSeckill() {
       //先判断缓存中是否有数据
       List<TbSeckillGoods> seckillGoods = redisTemplate.boundHashOps("seckillGoods").values();
       redisTemplate.delete("seckillGoods");
       //if(seckillGoods ==null || seckillGoods.size() <=0) {
       //没有 条件查询数据库放入缓存
       TbSeckillGoodsExample example = new TbSeckillGoodsExample();
       TbSeckillGoodsExample.Criteria criteria = example.createCriteria();
       criteria.andStatusEqualTo("1");//已审核
       criteria.andStockCountGreaterThan(0);//库存大于0
       Date now = new Date();
       criteria.andStartTimeLessThanOrEqualTo(now);//开始时间 <= now
       criteria.andEndTimeGreaterThanOrEqualTo(now);//结束时间 >= now
           System.out.println(now+">>>>>>>>>>>>>>>>>>>");
           seckillGoods = tbSeckillGoodsMapper.selectByExample(example);
       //遍历 放入缓存
       redisTemplate.setValueSerializer(new StringRedisSerializer());//序列化原因 1 是一旦使用原子性的自增操作  value使用这种方式序列化
       for (TbSeckillGoods seckillGood : seckillGoods) {
           redisTemplate.boundHashOps("seckillGoods").put(seckillGood.getId(), seckillGood);
           //查询时候需要将预减库存 放入redis中
           redisTemplate.boundValueOps("stockCount_" + seckillGood.getId()).set(seckillGood.getStockCount().toString());// 存储 也是字符串存储
       }

   }
}
